<template>
  <view class="follow-button" @click="handleClick">
    <button 
      class="btn" 
      :class="{ 'following': isFollowing }"
      :loading="loading"
    >
      {{ buttonText }}
    </button>
  </view>
</template>

<script>
import { userApi } from '@/utils/api.js';

export default {
  name: 'FollowButton',
  props: {
    userId: {
      type: [Number, String],
      required: true,
      validator: function(value) {
        // 确保userId不为null或undefined
        return value !== null && value !== undefined;
      }
    },
    initialFollowing: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isFollowing: this.initialFollowing,
      loading: false
    };
  },
  computed: {
    buttonText() {
      return this.isFollowing ? '已关注' : '关注';
    }
  },
  created() {
    // 检查关注状态
    this.checkFollowStatus();
  },
  methods: {
    async checkFollowStatus() {
      if (!this.userId) {
        console.warn('未提供有效的用户ID，无法检查关注状态');
        return;
      }
      
      try {
        const res = await userApi.checkFollowing(this.userId);
        if (res.code === 200) {
          this.isFollowing = res.data;
        }
      } catch (error) {
        console.error('检查关注状态失败:', error);
      }
    },
    
    async handleClick() {
      if (!this.userId) {
        console.warn('未提供有效的用户ID，无法执行关注/取消关注操作');
        return;
      }
      
      if (this.loading) return;
      
      this.loading = true;
      try {
        if (this.isFollowing) {
          // 取消关注
          const res = await userApi.unfollowUser(this.userId);
          if (res.code === 200) {
            this.isFollowing = false;
            uni.showToast({
              title: '已取消关注',
              icon: 'none'
            });
          }
        } else {
          // 关注
          const res = await userApi.followUser(this.userId);
          if (res.code === 200) {
            this.isFollowing = true;
            uni.showToast({
              title: '关注成功',
              icon: 'none'
            });
          }
        }
      } catch (error) {
        console.error('关注/取消关注操作失败:', error);
        uni.showToast({
          title: '操作失败，请稍后再试',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.follow-button {
  .btn {
    min-width: 120rpx;
    height: 60rpx;
    line-height: 60rpx;
    padding: 0 30rpx;
    border-radius: 30rpx;
    font-size: 28rpx;
    background-color: #FF69B4;
    color: #FFFFFF;
    border: none;
    
    &.following {
      background-color: #F5F5F5;
      color: #666666;
    }
    
    &[loading] {
      opacity: 0.7;
    }
  }
}
</style>
